package unq.persistencia;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

import conexion.AbstractHibernateTest;

/**
 * TODO: description
 */
public class SessionManager extends AbstractHibernateTest {

    private static SessionManager instance;

    private ThreadLocal<Session> threadSession = new ThreadLocal<Session>();

    private SessionFactory sessionFactory;

    private SessionManager() {
        this.setSessionFactory(super.getSessionFactory());
    }

    public static SessionManager getInstance() {
        if (SessionManager.instance == null) {
            SessionManager.instance = new SessionManager();
        }
        return instance;
    }

    public Session getSession() {
        if (this.threadSession.get() == null) {
            this.threadSession.set(super.getSessionFactory().openSession());
        }
        return this.threadSession.get();
    }

    @Override
    public SessionFactory getSessionFactory() {
        return this.sessionFactory;
    }

    public void setSessionFactory(final SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public void ejecutar(final Operaciones o) {
        Session session = this.getSession();
        Transaction t = session.beginTransaction();

        try {
            Long startTime = System.currentTimeMillis();

            o.generarYPersistir();

            Long endTime = System.currentTimeMillis();
            System.out.println("Tardo: " + (endTime - startTime));

            session.flush();
            session.getTransaction().commit();

            session.saveOrUpdate(o);
            session.flush();
            t.commit();

        } catch (Exception e) {
            t.rollback();
        } finally {
            session.close();
        }
    }

    public Query crearQuery(final String s) {
        Long startTime = System.currentTimeMillis();
        Query q = this.getSession().createQuery(s);
        Long endTime = System.currentTimeMillis();
        System.out.println("Tardo: " + (endTime - startTime));
        return q;
    }
}
